package com.qf.six.ssm.service.client.impl;

import com.qf.six.ssm.commen.exception.ServiceException;
import com.qf.six.ssm.commen.request.ClientDetailRequestParam;
import com.qf.six.ssm.commen.request.ClientParam;
import com.qf.six.ssm.commen.vo.ResponseCode;
import com.qf.six.ssm.commen.vo.ResponseResult;
import com.qf.six.ssm.entity.ClientUser;
import com.qf.six.ssm.mapper.client.ClientMapper;
import com.qf.six.ssm.service.client.ClientServiice;
import com.qf.six.ssm.service.clientDetail.ClientDetailService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * @author ZL
 */
@Service
public class ClientServiceImpl implements ClientServiice {
    @Resource
    ClientMapper clientMapper;
    @Resource
    ClientDetailService detailService;
    @Override
    public ResponseResult<Object> select(ClientParam param) {
        ClientUser user = clientMapper.select(param.getUsername());
        if(user != null){
            if(user.getPassword().equals(param.getPassword())){
                return ResponseResult.success(ResponseCode.SUCCESS);
            }else {
                return ResponseResult.error(ResponseCode.PASSWORD_ERROR);
            }
        }
        return ResponseResult.error(ResponseCode.USERNAME_ERROR);

    }

    @Override
    @Transactional
    public ResponseResult<Object> insert(ClientParam param) {
        ClientUser user = clientMapper.select(param.getUsername());
        if(user == null){
            int insert = clientMapper.insert(param);
            if(insert > 0){
                try {
                    int i = detailService.insertDetail(param.getUsername());
                    if(i > 0){
                        return ResponseResult.success(ResponseCode.SUCCESS);
                    }else{
                        throw new ServiceException(ResponseCode.ERROR);
                    }
                }catch (Exception e){
                    throw new ServiceException(ResponseCode.ERROR);
                }
            }else {
                throw new ServiceException(ResponseCode.ERROR);
            }
        }else {
            return ResponseResult.error(ResponseCode.REGISTER_ERROR);
        }
    }

    @Override
    public int update(ClientDetailRequestParam param) {
        int count = clientMapper.update(param);
        if(count > 0){
            return count;
        }else {
            throw new ServiceException(ResponseCode.ERROR);
        }
    }

}
